import Store from '../store';
import { replaceHtml, transformRangeToAbsolute, openSelfModel } from '../utils/util';
import { modelHTML } from './constant';
import sheetmanage from './sheetmanage';
import menuButton from './menuButton';
import { checkProtectionNotEnable } from './protection';
import { jfrefreshgrid } from '../global/refresh';
import locale from '../locale/locale';
import { setcellvalue } from '../global/setdata';
import { getRangeAxis, getRangeWithFlatten, getRange } from '../global/api';
import { checkCellInRange, checkRangeCrossing } from "../utils/matrix";
import dataVerificationCtrl from './dataVerificationCtrl';

function selHtml(id = null, st) {
    return `<select id="${id}" ${st && 'style="height:26px;margin-right: -81px;'} 
    opacity: 0;">
    <option value="0">查看</option>
    <option value="1">编辑</option>
    <option value="2">禁止查看</option>
</select>`
}
function roleSelHtml(id = null) {
    let ot;
    Store.roleList.forEach(item => {
        ot += `<option value="${item.role_id}">${item.name}</option>`
    });
    return `<select id="${id}" multiple="multiple">${ot}</select>`
}

let isInitialpermissionsModel = false;
let table;
let multipleSelect;
function initialpermissionsModelEvent() {
    const _locale = locale();
    const local_configPermissions = _locale.permissions;
    multipleSelect = $("#selectRole").multipleSelect({
        placeholder: "请选择",
        selectAll: false,
        width: "200",
        selectAllText: "全选",
        allSelected: '已全选',
        countSelected: '#项已选中',
    }).change((e) => {
        let filteredData = _.cloneDeep(Store.userList).filter(item => {
            if (multipleSelect.val()) {
                return isHasComm(multipleSelect.val().map(v => v * 1), item.roleIds)
            } else {
                return false
            }

        })
        table.clear();
        table.rows.add(filteredData);
        table.draw();
        $("#top-sel").val(0)
    })

    // 批量修改数据
    $("#top-sel").on('change', function (e) {
        let data = table.data();
        table.clear();
        table.rows.add(data.map(item => {
            item.operationAuthority = e.target.value
            return item
        }));
        table.draw();

    })
    $("#luckysheet-permissions-confirm").click(function () {
        let areaName = $("#luckysheet-input-area-name").val().trim();
        if (!areaName) return alert("请输入权限名称");
        let obj = Store.permissionList.find(item => item.name == areaName);
        if (obj) return alert("权限名称重复");
        let list = Array.from(table.data().map(item => {
            return {
                areaName: areaName,
                userId: item.userId,
                operationAuthority: item.operationAuthority,
                userRoleIds: item.roleIds.join(','),
                user_name: item.user_name

            }
        }))
        if (list.length===0) return alert("请添加设置用户");
        let rangeAxis = getRangeAxis().join(',');
        Store.permissionList.push({
            cellRange: rangeAxis,
            name: areaName,
            roleIds: multipleSelect.val().join(","),
            permissionSettingDetailList: list
        })
        $("#luckysheet-permissions-config").hide();
        $("#luckysheet-modal-dialog-mask").hide();
    });
}

function initialpermissionsModel(rangeAxis) {
    if (isInitialpermissionsModel) {
        multipleSelect.multipleSelect('uncheckAll')
        $("#luckysheet-input-area-idspan").html(rangeAxis);
        $("#luckysheet-input-area-name").val('');
        return;
    }

    isInitialpermissionsModel = true;
    const _locale = locale();
    const local_configPermissions = _locale.configPermissions;
    const locale_button = _locale.button;
    let opHtml = '';


    //Password input initial
    $("body").append(replaceHtml(modelHTML, {
        "id": "luckysheet-permissions-config",
        "addclass": "luckysheet-permissions-config",
        "title": "设置权限",
        "content": `
            <div>选区：<span id="luckysheet-input-area-idspan">${rangeAxis}</span> </div>
             <div style="margin-bottom:10px;">
                <label for="luckysheet-input-area-name">选区名称：<input id="luckysheet-input-area-name" name="luckysheet-protection-check-locked" autocomplete="off"></label>
            </div>
            <div>
                 ${roleSelHtml('selectRole')}
                ${selHtml('top-sel', 1)}
                <button class="btn btn-primary">批量设置</button>
            </div>
            <table id="example" class="cell-border stripe" >
                
            </table>
        `,
        "botton": `<button id="luckysheet-permissions-confirm" class="btn btn-primary">${locale_button.confirm}</button>
                    <button class="btn btn-default luckysheet-model-close-btn">${locale_button.cancel}</button>`,
        "style": "z-index:100003;width:500px;"
    }));

    initialpermissionsModelEvent();
}
function isHasComm(a, b) {
    let alt = a.length;
    let blt = b.length;
    let nlt = [...new Set(a.concat(b))].length;
    return alt + blt > nlt
}
// 设置权限
export function openSetPermissionsModel() {

    let rangeAxis = getRangeAxis().join(',');


    const _locale = locale();

    $("#luckysheet-rightclick-menu").hide();

    if (!checkProtectionNotEnable(Store.currentSheetIndex)) {
        return;
    }
    if (table) {
        table.destroy();
        $('#example').empty();
    }

    initialpermissionsModel(rangeAxis);
    openSelfModel("luckysheet-permissions-config");
    table = $('#example').DataTable({
        searching: false,
        paging: false,
        "info": false,//左下角信息
        "language": { "sEmptyTable": "暂无数据", },
        scrollY: 250,
        "columns": [
            {
                title: '角色', data: "roleIds",
                orderable: false,
                render: function (data, type, row, meta) {
                    let arr = data.map(item => {
                        return Store.roleList.find(v => v.role_id == item).name
                    })
                    return arr.join("，")
                }
            },
            { title: '用户名称', orderable: false, data: "user_name" },
            { title: '操作权限', orderable: false, data: "operationAuthority" }
        ],
        columnDefs: [{
            "targets": [2],
            createdCell: function (cell, cellData, rowData, rowIndex, colIndex) {
                $(cell).html(selHtml());
                var aInput = $(cell).find("select");
                aInput.val(cellData);
                $(cell).on("change", "select", function () {
                    let val = $(this).val()
                    table.cell(cell).data(val);
                    $(cell).html(selHtml());
                    var aInput = $(cell).find("select");
                    aInput.val(val);

                })

            }

        }],
        data: []

    })

}


// ---------------------------------------------------

let isInitialPermissionsViewModel = false;

let permissionsViewDataTable;
function initialPermissionsViewModel() {
    if (isInitialPermissionsViewModel) {
        return;
    }

    isInitialPermissionsViewModel = true;
    const _locale = locale();
    const locale_button = _locale.button;
    $("body").append(replaceHtml(modelHTML, {
        "id": "luckysheet-permissions-view",
        "addclass": "luckysheet-permissions-view",
        "title": "权限查看",
        "content": `
        <div style="position:relative;">
            <table id="permissionsViewTable" class="cell-border stripe" >
                
            </table>
            <div id="permissionsViewPerTableWrapDiv">
                <table id="permissionsViewPerTable">
                </table>
            </div>
        </div>
        `,
        "botton": "",
        "style": "z-index:1011;width:500px;"
    }));


}

function creatTable() {
    if (permissionsViewDataTable) {
        permissionsViewDataTable.destroy();
        $('#permissionsViewTable').empty();
    }
    let option = {
        searching: false,
        paging: false,
        "info": false,//左下角信息
        "language": { "sEmptyTable": "暂无数据", },
        "scrollY": "30vh",
        "columns": [
            {
                title: '序号', orderable: false, data: ""
            },
            {
                title: '区域', data: "name",
                orderable: false,
            },
            { title: '操作权限', orderable: false, data: "name", width: 80 }
        ],
        columnDefs: [
            {
                "targets": [0],
                render: function (a, b, c, { row }) {
                    return row + 1;
                }


            },
            {
                "targets": [1],
                render: function (a, b, c, d) {
                    return `<a  class="edit-per-perm" data-index=${d.row} style="cursor: pointer;color:#2D7FF9;">${a}</a>`;
                }


            },
            {
                "targets": [2],
                render: function (a, b, c, d) {
                    return `<a class="btn btn-primary del-area-abtn" data-index=${d.row}>删除</a>`;
                }
              
            }

        ],
        "rowCallback": function (row, data) {
          
            $(row).attr('data-area', data.cellRange);
            $(row).addClass('permissionsViewTable-tr')
           
        },
        data: Store.permissionList
    }
    permissionsViewDataTable = $('#permissionsViewTable').DataTable(option);
    permissionsViewDataTable.$($(".del-area-abtn")).click(function (e) {
        Store.permissionList.splice($(e.target).attr('data-index'), 1);
        creatTable()
    })
    permissionsViewDataTable.$($(".edit-per-perm")).click(function (e) {
        $("#permissionsViewPerTableWrapDiv").dialog({ modal: true, width: 500, top: 0, title: '详情' });
        creatPerTabele(Store.permissionList[$(e.target).attr('data-index') * 1])
    })
    permissionsViewDataTable.$($('.permissionsViewTable-tr')).on("mouseover", function () {
        let arr = $(this).attr('data-area').split(',')
        $(this).addClass('trhover');
        try {
            luckysheet.setRangeShow(arr);
        } catch (error) {
            console.log(error)
        }
    }).on("mouseleave", function () {
        if ($(this).hasClass('trhover')) {
            $(this).removeClass('trhover')
        }

    })
}
let permissionsViewPerTable
function creatPerTabele(paramData) {
    if (permissionsViewPerTable) {
        permissionsViewPerTable.destroy();
        $('#permissionsViewPerTable').empty();
    }
    let option = {
        searching: false,
        paging: false,
        "info": false,//左下角信息
        "language": { "sEmptyTable": "暂无数据", },
        "scrollY": "30vh",
        "columns": [
            { title: '用户名称', orderable: false, },
            {
                title: '区域', orderable: false,

            },
            { title: '操作权限', orderable: false, data: "operationAuthority" }
        ],
        columnDefs: [{
            "targets": [0],
            render: function (a, b, row, d) {
                if (row.user_name) {
                    return row.user_name
                } else {
                    let obj = Store.userList.find(v => v.userId == row.userId);
                    return obj ? obj.user_name : '用户不存在'
                }
            }
        },
        {
            "targets": [1],
            render: function (a, b, row, d) {
                if (row.areaName) {
                    return row.areaName
                } else {
                    return paramData.name
                }
            }
        },
        {
            "targets": [2],
            createdCell: function (cell, cellData, rowData, rowIndex, colIndex) {
                $(cell).html(selHtml());
                var aInput = $(cell).find("select");
                aInput.val(cellData);
                $(cell).on("change", "select", function () {
                    let val = $(this).val()
                    permissionsViewPerTable.cell(cell).data(val);
                    $(cell).html(selHtml());
                    var aInput = $(cell).find("select");
                    aInput.val(val);

                })

            },
        }],
        data: paramData.permissionSettingDetailList

    }
    permissionsViewPerTable = $("#permissionsViewPerTable").DataTable(option);

}
// 权限查看
export function openPermissionsViewModel() {
    initialPermissionsViewModel()
    openSelfModel("luckysheet-permissions-view");
    // 创建表格
    creatTable()
}
